package com.vmix.android.vmixsdk.rds;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

public class FileUploadService extends Service {
	
	// define a broadcast type
	public static final String UPLOAD_COMPLETE = "upload_complete";
	
	// newly created media id
	private String mediaId;
	
	private FileUploadOperation operation = null;
	
	public Thread thread;
	
	public final IBinder binder = new FileUploadBinder();
	
	private String filePath = "";
	private String title="";
	private String author="";
	
	/**
	 * @see android.app.Service#onBind(Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	/**
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
	}

	/**
	 * @see android.app.Service#onStartCommand(Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Bundle bundle = intent.getExtras();
		
		this.filePath = bundle.getString("filePath");
		this.title = bundle.getString("title");
		this.author = bundle.getString("author");
		
		this.thread = new Thread( null, this.doBackgroundThreadProcessing, "fileUploadOperationThread");
		
		// start the thread
		this.thread.start();

		return Service.START_STICKY;
	}
	
	/**
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
	
		this.stopThreads();
		
		super.onDestroy();
	}
	
	/**
	 * Custom binder for this service
	 * 
	 * @author lei
	 *
	 */
	public class FileUploadBinder extends Binder {
	
		public FileUploadService getService() {
			return FileUploadService.this;
			
		}
	}
	
	/**
	 * Getter
	 * 
	 * @return String
	 */
	public String getMediaId() {
		return this.mediaId;
	}
	
	// create the private runnable for background processing
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		
		public void run() {
		
			performFileUpload();
			
		}
		
	};
	
	// call upon the fileUploadOperation to execute the file upload
	private void performFileUpload() {
		try {
			
			this.operation = new FileUploadOperation( this.filePath, this.title, this.author);
			
			this.mediaId = this.operation.process();
			
			// handle the completion
			this.onLoadComplete();
			
		}
		catch( Exception e ) {
			// TODO
		}
	}
	
	/**
	 * broadcast the intent to say that we're finished with the upload
	 */
	private void onLoadComplete() {
		
		// create new intent
		Intent intent = new Intent( FileUploadService.UPLOAD_COMPLETE );
		
		// broadcast
		sendBroadcast( intent );
		
	}
	
	// stopping all the running threads
	private void stopThreads() {
		
		// stopping
		if( this.thread.isAlive() ) {
		
			this.thread.stop();
		}
	}
}
